package com.newenergy.wisehome.ui.fragment;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;

/**
 * Created by dell on 2016/11/29.
 */

public class FragmentHelper {


    /**
     * 销毁上一个fragment,重新加载新的fragment
     */

    public static void replaceFragment(AppCompatActivity mainActivity,
                                       int containerId, Class<?
            extends BaseFragment> fragmentClazz , Object data) {
//        if (mainActivity.recordFragments.contains(fragmentClazz)) {
//            mainActivity.recordFragments.remove(fragmentClazz);
//        }
//        mainActivity.recordFragments.add(fragmentClazz);
        FragmentManager fragmentManager = mainActivity
                .getSupportFragmentManager();
        String tag = fragmentClazz.getSimpleName();
        BaseFragment fragment = (BaseFragment) fragmentManager
                .findFragmentByTag(tag);

        if (fragment == null) {
            try {
                fragment = fragmentClazz.newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (data != null) {
            fragment.setData(data);
        }

        FragmentTransaction transaction = fragmentManager
                .beginTransaction();
        transaction.addToBackStack(tag);
        transaction.replace(containerId, fragment, tag).commit();
    }


    //    /**
//     * 销毁上一个fragment,重新加载新的fragment
//     */
//
//    public static void replaceFragment(MainActivity mainActivity,
//                                       int containerId, Class<?
// extends BaseFragment> fragmentClazz) {
//
//        if (mainActivity.recordFragments.contains(fragmentClazz)) {
//            mainActivity.recordFragments.remove(fragmentClazz);
//        }
//        mainActivity.recordFragments.add(fragmentClazz);
//        FragmentManager manager = mainActivity
// .getSupportFragmentManager();
//        String tag = fragmentClazz.getSimpleName();
//
//      Fragment fragment = manager.findFragmentByTag(tag);
//
//        if (fragment == null) {
//            try {
//                fragment = fragmentClazz.newInstance();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        android.support.v4.app.FragmentTransaction transaction =
// manager.beginTransaction();
//        transaction.addToBackStack(tag);
//        transaction.replace(containerId, fragment, tag).commit();
//
//
//    }

}
